package lvjia.site.ai;

import de.themoep.minedown.MineDown;
import de.themoep.minedown.MineDownParser;
import net.md_5.bungee.api.chat.BaseComponent;
import okhttp3.*;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;

import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;


import static lvjia.site.ai.ver.upurl;


public final class Ai extends JavaPlugin implements Listener {
    private static final Logger LOGGER = LoggerFactory.getLogger(Ai.class);
    private OkHttpClient httpClient;
    private ExecutorService executorService;
    private String modelname;
    private  String  key=null;


    public File customConfigFile;
    private FileConfiguration customConfig;
    @Override
    public void onEnable() {
        createCustomConfig();
        final OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(upurl)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseData = response.body().string();
                    double serverVer = Double.parseDouble(responseData);

                    if (ver.ver == serverVer) {
                        LOGGER.info("AI对话当前为最新版");
                        Bukkit.broadcastMessage("AI对话当前为最新版");
                    } else {
                        LOGGER.info("AI对话有新版本！在https://file.mingpixel.site 查看，当前版本为" + ver.ver + ",最新版为" + serverVer);
                        Bukkit.broadcastMessage("AI对话有新版本！在https://file.mingpixel.site 查看，当前版本为" + ver.ver + ",最新版为" + serverVer);
                    }
                } else {
                    Bukkit.broadcastMessage("AI对话检查更新失败");
                    LOGGER.info("AI对话检查更新失败");
                }
            }
        });


        Bukkit.getPluginCommand("ai").setExecutor(this);
        getServer().getPluginManager().registerEvents(new PlayerJoinListener(), this);
        System.setProperty("file.encoding", "UTF-8");
        Bukkit.getServer().getConsoleSender().sendMessage("AI插件已成功启动!");
        httpClient = new OkHttpClient.Builder().connectTimeout(30, TimeUnit.SECONDS).writeTimeout(30, TimeUnit.SECONDS).readTimeout(30, TimeUnit.SECONDS).callTimeout(30, TimeUnit.SECONDS).build();
        executorService = Executors.newFixedThreadPool(10);
        getServer().getPluginManager().registerEvents(this, this);
        LOGGER.info("AI对话插件已加载！"+ver.ver+"版");
    }

@Override
public void onDisable() {
    if (executorService != null) {
        executorService.shutdown();
        try {
            if (!executorService.awaitTermination(5, TimeUnit.SECONDS)) {
                executorService.shutdownNow();
                if (!executorService.awaitTermination(5, TimeUnit.SECONDS))
                    LOGGER.error("Executor service did not terminate gracefully.");
            }
        } catch (InterruptedException ie) {
            executorService.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }
}

    @Override
   public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
    if (command.getName().equalsIgnoreCase("ai")) {
        if (!(sender instanceof Player player)) {
            sender.sendMessage("只有玩家可以执行此命令！Only players can execute this command!");
            return false;
        }
        if (args.length > 0) {
            String message = String.join(" ", args);
            sender.sendMessage("已经向AI发送了，请耐心等待");
            executorService.execute(() -> {
                LOGGER.info("[{}] said: {}", player.getName(), message);
                String aiResponse = sendChatToAiServer((Player) sender, message);
                if (aiResponse != null) {
                    MineDown mineDown = new MineDown(aiResponse);
                    mineDown.enable(MineDownParser.Option.LEGACY_COLORS);
                    BaseComponent[] components = mineDown.toComponent();
                    String legacyText = BaseComponent.toLegacyText(components);
                    Bukkit.broadcastMessage("<" + player.getName() + "> " + message + "\n" + legacyText);
                } else {
                    LOGGER.error("AI服务器返回空响应");
                    sender.sendMessage("AI服务器返回空响应");
                }
            });
            return true;
        } else {
            sender.sendMessage("/ai [任意内容]");
            return false;
        }
    }
    return true;
}


    public String sendChatToAiServer(Player player, String message) {
    String model = customConfig.getString("model");
    modelname = getModelName(model);
if(Objects.equals(model, "Qwen")){
    Qwen qwen = new Qwen();
    String key = customConfig.getString("QwenAPIKEY");
    String response = qwen.executeRequest(message,key);
    if (response == null) {
        return null;
    }
    return modelname + "-AI：" + response;
    } else

    if (Objects.equals(model, "kimi")) {
        Kimi kimi = new Kimi();
        String key = customConfig.getString("kimikey");
        String response = kimi.executeRequest(message,key);
        if (response == null) {
            return null;
        }
        return modelname + "-AI：" + response;
    } else {
        try (Response response = sendRequestToAiServer(model, message)) {
            if (response.isSuccessful()) return modelname + "-AI：" + response.body().string();
            else {
                LOGGER.error("Request to the AI server failed with status code: {}", response.code());
                Bukkit.broadcastMessage("请求AI服务器失败");
                return null;
            }
        } catch (IOException e) {
            LOGGER.error("An IOException occurred while communicating with the AI server:", e);
            return null;
        }
    }
}

static String getModelName(String model) {
    return switch (model) {
        case "Qwen4" -> "通义千问";
        case "gpt35free" -> "gpt-3.5-turbo";
        case "kimi" -> "Kimi";
        case "openai" -> "OpenAI";
        case "Qwen" -> "通义千问网页版";
        default -> "未知|错误";
    };
}

private Response sendRequestToAiServer(String model, String message) throws IOException {
    if (Objects.equals(model, "openai")){
        //连接到openai的服务，https://api.openai.com/v1/chat/completions ，同时需要写入系统提示此，按照curl https://api.openai.com/v1/chat/completions -H "Content-Type: application/json" -H "Authorization: Bearer $OPENAI_API_KEY" -d '{ "model": "gpt-3.5-turbo", "messages": [{"role": "user", "content": "Hello!"}] }'

        String openaiKey = customConfig.getString("openaiKey");
        String openaiModel = customConfig.getString("openaiModel");
        HttpUrl url = Objects.requireNonNull(HttpUrl.parse("https://api.openai.com/v1/chat/completions")).newBuilder().build();
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), """
                {
                    "model": "%s",
                    "messages": [
                    {
                    "role": "system",
                    "content": "默认为minecraft相关内容，玩家在minecraft聊天栏中对话，不支持连续对话。先说中文。"
                    },
                        {
                            "role": "user",
                            "content": "%s"
                        }
                    ]
                }
                """.formatted(openaiModel, message));
        Request request = new Request.Builder().url(url).addHeader("Content-Type", "application/json").addHeader("Authorization", "Bearer " + openaiKey).post(body).build();
        return httpClient.newCall(request).execute();
    }
       else{
    HttpUrl url = Objects.requireNonNull(HttpUrl.parse("https://mingpixel.site/" + model + ".php")).newBuilder().addQueryParameter("text", message).build();
    Request request = new Request.Builder().url(url).build();
    return httpClient.newCall(request).execute();
}}
   private void createCustomConfig() {
    customConfigFile = new File(getDataFolder(), "lvai.yml");
    if (!customConfigFile.exists()) {
        customConfigFile.getParentFile().mkdirs();
        saveResource("lvai.yml", false);
    }

    customConfig = new YamlConfiguration();
    try {
        customConfig.load(customConfigFile);
    } catch (IOException | InvalidConfigurationException e) {
        e.printStackTrace();
    }

    // 设置默认值
    customConfig.addDefault("model", "Qwen");
       customConfig.addDefault("kimikey", "输入kimi的key，无需付费，从官网获取");
       customConfig.addDefault("提示", """
               # 目前可以填入'Qwen4'和'gpt35free'和kimi和openai 四个值，分别对应通义千问和gpt-3.5-turbo和kimi模型与openai服务，Qweni为 通义千问网页版。
               # 现在可以填入"kimi"，支持联网，方法：打开 kimi.moonshot.cn 或者 kimi.ai ，登录，按下F12，打开“应用程序”，（如没找到，点击“加号”，其在Edge鼠标悬浮显示为更多工具），
               # 找到“存储”，“本地存储”，找到“refresh_token”，右键“编辑‘值’”，再次右键进行复制，粘贴kimikey中
               模型列表：Qwen4    gpt35free    kimi      openai    Qwen
               """);
       customConfig.addDefault("openaiKey", "如果你打算直接使用openai的服务，就填写该字段为openAI-key，否则就别管了");
       customConfig.addDefault("QwenAPIKEY", "从通义千问网页版获取的key");
         customConfig.addDefault("openaiModel", "如果你打算直接使用openai的服务，就填写该字段为模型名字，否则就别管了");

    // 确保默认值被复制到配置文件中
    customConfig.options().copyDefaults(true);

    // 保存配置文件
    try {
        customConfig.save(customConfigFile);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}
